//
//  RCMainVC.swift
//  RunChuanThermometer
//
//  Created by 李东 on 2024/4/16.
//

import UIKit
import SnapKit
import CoreLocation


class RCMainVC: RCBaseVC {

    var isTem = false
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        initUI()
        NotificationCenter.default.addObserver(self, selector: #selector(showAd), name: .SDKInitFinish, object: nil)
    }
    
    @objc func showAd() {
        if AppProducts.shared.isPurchased {
            adHelper.removeBannerView()
        }else{
            if hasLoadAd {
                return
            }
            hasLoadAd = true
            adHelper.loadBanner(currentVC: self, isMainVC: false)
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if ADManager.initFinish {
            showAd()
        }
    }
    
    
    lazy var scrollView: UIScrollView = {
        let temp = UIScrollView()
        temp.contentInsetAdjustmentBehavior = .never
        return temp
    }()
    
    lazy var topImgView: UIImageView = {
        let temp = UIImageView(image: UIImage(named: "img_home_top"))
        temp.contentMode = .scaleAspectFill
        temp.backgroundColor = .init(hex: 0xFCF2E6)
        return temp
    }()
    
    lazy var setupBtn: UIButton = {
        let temp = UIButton(type: .custom)
        temp.setImage(UIImage(named: "icon_setup"), for: .normal)
        temp.addTarget(self, action: #selector(setupHandle), for: .touchUpInside)
        return temp
    }()
    
    lazy var bgView: UIView = {
        let temp = UIView()
        temp.backgroundColor = .white
        temp.layer.cornerRadius = 20
        temp.layer.masksToBounds = true
        return temp
    }()
    
    lazy var itemBtn1: UIButton = {
        let temp = UIButton(type: .custom)
        temp.tag = 10
        temp.setImage(UIImage(named: "img_home_item1"), for: .normal)
        temp.addTarget(self, action: #selector(itemHandle(sender:)), for: .touchUpInside)
        return temp
    }()
    
    lazy var itemBtn2: UIButton = {
        let temp = UIButton(type: .custom)
        temp.tag = 20
        temp.setImage(UIImage(named: "img_home_item2"), for: .normal)
        temp.addTarget(self, action: #selector(itemHandle(sender:)), for: .touchUpInside)
        return temp
    }()
    
    lazy var itemBtn3: UIButton = {
        let temp = UIButton(type: .custom)
        temp.tag = 30
        temp.setImage(UIImage(named: "img_home_item3"), for: .normal)
        temp.addTarget(self, action: #selector(itemHandle(sender:)), for: .touchUpInside)
        return temp
    }()
    
    lazy var locationManager: CLLocationManager = {
        let temp = CLLocationManager()
        temp.delegate = self
        temp.distanceFilter = kCLLocationAccuracyBest
        return temp
    }()
    
    
    func startLocation() {
        if CLLocationManager.authorizationStatus() == .denied || CLLocationManager.authorizationStatus() == .restricted {
            RXPermissionUtils.showSystemAlert(title: NSLocalizedString("无法获取定位", comment: ""), message: NSLocalizedString("请在iPhone的设置中，授权app访问定位", comment: ""))
            return
        }
        locationManager.requestLocation()
    }
    
    
    @objc func setupHandle() {
        navigationController?.pushViewController(RCSetupVC(), animated: true)
    }
    
    @objc func itemHandle(sender: UIButton) {
        if !AppProducts.shared.isPurchased {
            showSubVC()
            return
        }
        switch sender.tag {
        case 10:
            isTem = true
            if AppConfig.lat != 0 && AppConfig.lon != 0 {
                self.navigationController?.pushViewController(RCWebVC(url: (AppConfig.H5_URL_Tem + "?lat=\(AppConfig.lat)&lon=\(AppConfig.lon)")), animated: true)
            }else{
                startLocation()
            }
            break
        case 20:
            isTem = false
            if AppConfig.lat != 0 && AppConfig.lon != 0 {
                self.navigationController?.pushViewController(RCWebVC(url: (AppConfig.H5_URL_Hum + "?lat=\(AppConfig.lat)&lon=\(AppConfig.lon)")), animated: true)
            }else{
                startLocation()
            }
            break
        case 30:
            navigationController?.pushViewController(RCVoiceVC(), animated: true)
            break
        default:
            break
        }
    }


}

extension RCMainVC: CLLocationManagerDelegate {
    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        switch status {
        case .notDetermined:
            manager.requestAlwaysAuthorization()
            break
        case .restricted:
            RXPermissionUtils.showSystemAlert(title: NSLocalizedString("无法使用定位", comment: ""), message: NSLocalizedString("请在iPhone的设置中，授权app访问定位", comment: ""))
            manager.stopUpdatingLocation()
            break
        case .denied:
            manager.stopUpdatingLocation()
            RXPermissionUtils.showSystemAlert(title: NSLocalizedString("无法使用定位", comment: ""), message: NSLocalizedString("请在iPhone的设置中，授权app访问定位", comment: ""))
            break
        default:
            locationManager.startUpdatingLocation()
            break
        }
    }
    
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
     
    }
    
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if AppConfig.lat != 0 && AppConfig.lon != 0 {
            return
        }
        guard let lacation = locations.last else {
            return
        }
        AppConfig.lat = lacation.coordinate.latitude
        AppConfig.lon = lacation.coordinate.longitude
//        let coder = CLGeocoder()
//        coder.reverseGeocodeLocation(lacation) {[weak self] (data, error) in
//            if !AppConfig.city.isEmpty {
//                return
//            }
//            if error != nil || data == nil || data!.isEmpty {
//                return
//            }
//            guard let mark = data?.first else {
//                return
//            }
//            AppConfig.city = mark.locality ?? ""
        if isTem {
            self.navigationController?.pushViewController(RCWebVC(url: (AppConfig.H5_URL_Tem + "?lat=\(AppConfig.lat)&lon=\(AppConfig.lon)")), animated: true)
        }else{
            self.navigationController?.pushViewController(RCWebVC(url: (AppConfig.H5_URL_Hum + "?lat=\(AppConfig.lat)&lon=\(AppConfig.lon)")), animated: true)
        }
        self.locationManager.stopUpdatingLocation()
//        }
    }
}


extension RCMainVC {
    func initUI() {
        hideNavgaitionBar()
        view.addSubview(scrollView)
        scrollView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        scrollView.addSubview(topImgView)
        topImgView.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.width.equalTo(view)
            make.height.equalTo(CGFloat.aspect(value: 432))
        }
        
        scrollView.addSubview(setupBtn)
        setupBtn.snp.makeConstraints { make in
            make.top.equalTo(CGFloat.topPadding)
            make.height.width.equalTo(44)
            make.right.equalTo(-10)
        }
        
        scrollView.addSubview(bgView)
        bgView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview()
            make.top.equalTo(topImgView.snp.bottom).offset(-20)
        }
        
        bgView.addSubview(itemBtn1)
        itemBtn1.snp.makeConstraints { make in
            make.top.equalTo(15)
            make.centerX.equalToSuperview()
        }
        
        bgView.addSubview(itemBtn2)
        itemBtn2.snp.makeConstraints { make in
            make.top.equalTo(itemBtn1.snp.bottom).offset(15)
            make.centerX.equalToSuperview()
        }
        
        bgView.addSubview(itemBtn3)
        itemBtn3.snp.makeConstraints { make in
            make.top.equalTo(itemBtn2.snp.bottom).offset(15)
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview().offset(-100)
        }
    }
}
